package servlet;

import com.mysql.jdbc.PreparedStatement;
import model.Commodity;
import util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/SaveCommodityDitServlet.do")
public class SaveCommodityDitServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int CID = Integer.parseInt(request.getParameter("cid"));
        int NUMBER = Integer.parseInt(request.getParameter("number"));
        float PRICE = Float.parseFloat(request.getParameter("price"));
        String C_NAME = request.getParameter("c_name");
        String PHOTO = request.getParameter("photo");
        List<Commodity> commodities = new ArrayList<>();
        Connection conn = null;
        try { // 创建PreparedStatement
            conn = DBHelper.getConnection();


            String sql2 = "SELECT photo FROM commodity where cid="+CID;
            Statement stmt1 = conn.createStatement();
            ResultSet rs2 = stmt1.executeQuery(sql2);
            if (rs2.next() && (PHOTO == null || PHOTO == "")){
                PHOTO = rs2.getString("photo");
            }else{
                PHOTO = "images/" + PHOTO;
            }


            String sql = "UPDATE commodity set  c_name=?,number=?, price=?,photo=? where cid=?";
            PreparedStatement pastas = (PreparedStatement) conn.prepareStatement(sql);
            // PreparedStatement赋值
            pastas.setString(1, C_NAME );
            pastas.setInt(2, NUMBER);
            pastas.setFloat(3, PRICE);
            pastas.setString(4, PHOTO);
            pastas.setInt(5, CID);
            // 执行
            pastas.execute();


            String sql1 = "SELECT cid,number,price,c_name,photo FROM commodity";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql1);
            while (rs.next()){
                Commodity commodity = new Commodity(rs.getInt("cid"),
                        rs.getInt("number"),
                        rs.getFloat("price"),
                        rs.getString("c_name"),
                        rs.getString("photo"));
                commodities.add(commodity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getSession().setAttribute("commodities",commodities);
        request.getRequestDispatcher("AdminCommodity.jsp").forward(request,response);
    }
}
